package com.kuiandjie.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.kuiandjie.entity.Employee;
import com.kuiandjie.entity.IdeaComment;
import com.kuiandjie.entity.Log;
import com.kuiandjie.entity.Project;
import com.kuiandjie.service.IdeaCommentService;
import com.kuiandjie.service.LogService;
import com.kuiandjie.util.DateUtil;

public class IdeaCommentServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		Project curp = (Project) session.getAttribute("curp");
		if(curp != null) {
			if("POST".equals(request.getMethod())) {
				Employee e = (Employee) session.getAttribute("employee");
				String lastTime = request.getParameter("time");
				int ideaId = Integer.parseInt(request.getParameter("ideaid"));
				int commentId = Integer.parseInt(request.getParameter("commentid"));
				String comment = request.getParameter("comment");
				String title = request.getParameter("title");
				
				IdeaComment ic = new IdeaComment();
				ic.setContent(comment);
				ic.setEmployeeId(e.getId());
				ic.setIdeaId(ideaId);
				ic.setCreatetime(DateUtil.getNow());
				IdeaCommentService ics = new IdeaCommentService();
				int id = ics.insertComment(ic);
				
				if(id != -1) {
					Log log = new Log();
					log.setDesc("评论了想法<a href='showidea.jspx?id='"+ ideaId +">" + title + "</a>");
					log.setEmployeeId(e.getId());
					log.setProjectId(curp.getId());
					log.setTime(DateUtil.getNow());
					log.setName(e.getName());
					log.setPic(e.getPic());
					
					LogService ls = new LogService();
					ls.inserLog(log);
					
					request.setAttribute("msg", new Gson().toJson(log));
					request.getRequestDispatcher("msgflow.jspx").include(request, response);
				}
				List<IdeaComment> list = ics.getCommentByIdAndTime(ideaId, lastTime, commentId);
				
				response.setContentType("application/json;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");
				PrintWriter out = response.getWriter();
				
				out.print(new Gson().toJson(list));
				out.flush();
				out.close();
			}
		} else {
			response.sendRedirect("main.jspx");
		}
	}
}
